package com.tomshushu.doc.freedoc.modular.teamuser.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tomshushu.doc.freedoc.core.exception.ServiceException;
import com.tomshushu.doc.freedoc.core.factory.PageFactory;
import com.tomshushu.doc.freedoc.core.model.result.PageResult;
import com.tomshushu.doc.freedoc.modular.project.entity.ProjectEntity;
import com.tomshushu.doc.freedoc.modular.project.service.ProjectService;
import com.tomshushu.doc.freedoc.modular.projectuser.entity.ProjectUserEntity;
import com.tomshushu.doc.freedoc.modular.projectuser.service.ProjectUserService;
import com.tomshushu.doc.freedoc.modular.teamuser.entity.TeamUserEntity;
import com.tomshushu.doc.freedoc.modular.teamuser.mapper.TeamUserMapper;
import com.tomshushu.doc.freedoc.modular.teamuser.model.param.SetDefaultTeamParam;
import com.tomshushu.doc.freedoc.modular.teamuser.model.param.TeamUserParam;
import com.tomshushu.doc.freedoc.modular.teamuser.model.param.TeamUserQueryParam;
import com.tomshushu.doc.freedoc.modular.teamuser.model.result.TeamUserResult;
import com.tomshushu.doc.freedoc.modular.teamuser.service.TeamUserService;
import com.tomshushu.doc.freedoc.modular.user.entity.UserEntity;
import com.tomshushu.doc.freedoc.modular.user.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: zhouhong
 * @date: 2025-06-11 12:30
 * @version: 1.0
 */
@Service
public class TeamUserServiceImpl extends ServiceImpl<TeamUserMapper, TeamUserEntity> implements TeamUserService {

    @Resource
    private UserService userService;
    @Resource
    private ProjectUserService projectUserService;
    @Resource
    private ProjectService projectService;

    @Override
    public void addTeamUser(TeamUserParam teamUserParam) {
        if (teamUserParam.getTeamUserList().isEmpty()) {
            return;
        }
        teamUserParam.getTeamUserList().forEach(item -> {
            // 校验是否已经关联
            long count = this.count(new QueryWrapper<TeamUserEntity>()
                    .eq("user_id", item.getUserId())
                    .eq("team_id", item.getTeamId()));
            if (count > 0) {
                throw new ServiceException(7003, "用户已关联");
            }
            TeamUserEntity teamUserEntity = new TeamUserEntity();
            BeanUtils.copyProperties(item, teamUserEntity);
            if (ObjectUtil.isNull(item.getType())) {
                teamUserEntity.setType("PARTICIPANT");
            }
            save(teamUserEntity);
        });
    }

    @Override
    public void deleteTeamUser(TeamUserParam teamUserParam) {
        if (teamUserParam.getTeamUserList().isEmpty()) {
            return;
        }
        teamUserParam.getTeamUserList().forEach(item -> {
            this.remove(new LambdaQueryWrapper<TeamUserEntity>()
                    .eq(TeamUserEntity::getUserId, item.getUserId())
                    .eq(TeamUserEntity::getTeamId, item.getTeamId())
                    .ne(TeamUserEntity::getType, "OWNER"));

            // 退出当前团队的所有项目
            List<ProjectEntity> projectEntityList = projectService.list(new LambdaQueryWrapper<ProjectEntity>()
                    .eq(ProjectEntity::getTeamId, item.getTeamId()));
            projectEntityList.forEach(project -> {
                projectUserService.remove(new LambdaQueryWrapper<ProjectUserEntity>()
                        .eq(ProjectUserEntity::getProjectId, project.getProjectId())
                        .eq(ProjectUserEntity::getUserId, item.getUserId()));
            });
        });
    }

    @Override
    public PageResult<TeamUserResult> pageUserByTeamId(TeamUserQueryParam param) {
        LambdaQueryWrapper<TeamUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(param.getTeamId())) {
            queryWrapper.eq(TeamUserEntity::getTeamId, param.getTeamId());
        }
        Page<TeamUserEntity> page = this.page(PageFactory.defaultPage(), queryWrapper);
        Page<TeamUserResult> resPage = new Page<>();
        BeanUtil.copyProperties(page, resPage);
        List<TeamUserResult> resultList = new ArrayList<>();
        page.getRecords().forEach(item -> {
            TeamUserResult result = new TeamUserResult();
            // 获取用户
            UserEntity user = userService.getById(item.getUserId());
            BeanUtil.copyProperties(user, result);
            result.setType(item.getType());
            resultList.add(result);
        });
        resPage.setRecords(resultList);
        return new PageResult<>(resPage);
    }

    @Override
    public PageResult<TeamUserResult> pageUnUnionUser(TeamUserQueryParam param) {
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.apply(
                "user_id NOT IN (SELECT user_id FROM doc_team_user WHERE team_id = {0})",
                param.getTeamId()
        );
        Page<UserEntity> page = userService.page(PageFactory.defaultPage(), queryWrapper);
        Page<TeamUserResult> resPage = new Page<>();
        BeanUtil.copyProperties(page, resPage);
        List<TeamUserResult> resultList = new ArrayList<>();
        page.getRecords().forEach(userEntity -> {
            TeamUserResult teamUserResult = new TeamUserResult();
            BeanUtil.copyProperties(userEntity, teamUserResult);

            resultList.add(teamUserResult);
        });
        resPage.setRecords(resultList);
        return new PageResult<>(resPage);
    }

    public void setDefaultTeam(@RequestBody SetDefaultTeamParam param){
        if (ObjectUtil.isNull(param.getTeamId())) {
            return;
        }
        String userId = StpUtil.getLoginIdAsString();
        // 将之前的默认项目设置为非默认（使用list放置getOne 获取多条记录）
        List<TeamUserEntity> defaultTeamList = this.list(new LambdaQueryWrapper<TeamUserEntity>()
                .eq(TeamUserEntity::getUserId, userId)
                .eq(TeamUserEntity::getIsDefault, true));
        defaultTeamList.forEach(item -> {
            item.setIsDefault(false);
            this.updateById(item);
        });
        TeamUserEntity teamUserEntity = this.getOne(new LambdaQueryWrapper<TeamUserEntity>()
                .eq(TeamUserEntity::getUserId, userId)
                .eq(TeamUserEntity::getTeamId, param.getTeamId()));
        teamUserEntity.setIsDefault(true);
        this.updateById(teamUserEntity);
    }
}
